package com.spark.modules.generation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spark.common.core.Result;
import com.spark.common.core.api.SparkCommonApi;
import com.spark.common.core.entity.model.DataSourceTablesModel;
import com.spark.common.core.entity.generation.vo.CreateModelVo;
import com.spark.common.core.entity.online.OnlineDataSource;
import com.spark.common.exception.SparkException;
import com.spark.common.utils.CreateTableUtils;
import com.spark.common.utils.DataSourceUtils;
import com.spark.common.core.entity.generation.GenModel;
import com.spark.common.core.entity.generation.GenModelFields;
import com.spark.modules.generation.mapper.GenModelFieldsMapper;
import com.spark.modules.generation.mapper.GenModelMapper;
import com.spark.modules.generation.service.IGenModelService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 模型Service
 *
 * @author LYCHEE
 * @date 2025/02/24 15:23
 */
@Service
public class GenModelServiceImpl extends ServiceImpl<GenModelMapper, GenModel> implements IGenModelService {

    @Resource
    private SparkCommonApi sparkCommonApi;
    @Resource
    private GenModelFieldsMapper genModelFieldsMapper;

    /**
     * 是否已经存在模型名称
     *
     * @param modelName 模型名称
     * @return 是否存在
     */
    @Override
    public Result<?> existModelName(String modelName) {
        OnlineDataSource dataSource = sparkCommonApi.queryDefaultDataSource();
        if (Objects.isNull(dataSource)) {
            return Result.fail("请配置默认数据源");
        }
        try {
            DataSourceUtils dataSourceUtils = new DataSourceUtils(dataSource.getDbDriver()
                    , dataSource.getDbUrl(), dataSource.getDbUsername(), dataSource.getDbPassword());
            List<DataSourceTablesModel> tablesModels = dataSourceUtils.queryAllTablesInfo();
            if (!CollectionUtils.isEmpty(tablesModels)) {
                Set<String> existingTableNamesSet = tablesModels.stream()
                        .map(DataSourceTablesModel::getTableName)
                        .collect(Collectors.toSet());
                if (existingTableNamesSet.contains(modelName)) {
                    return Result.ok(true);
                }
            }
            List<GenModel> existTableNames = baseMapper.selectList(new QueryWrapper<>());
            Set<String> existingTableNamesSet = existTableNames.stream()
                    .map(GenModel::getModelCode)
                    .collect(Collectors.toSet());
            if (existingTableNamesSet.contains(modelName)) {
                return Result.ok(true);
            }
            return Result.ok(false);
        } catch (Exception e) {
            throw new SparkException(e.getMessage());
        }
    }

    /**
     * 同步模型结构
     *
     * @param modelId 模型ID
     * @return 是否成功
     */
    @Override
    public Result<?> syncModel(String modelId) {
        GenModel genModel = baseMapper.selectById(modelId);
        if (Objects.isNull(genModel)) {
            return Result.fail("暂无模型信息");
        }
        LambdaQueryWrapper<GenModelFields> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenModelFields::getModelId, modelId).orderByAsc(GenModelFields::getCreateTime);
        List<GenModelFields> genModelFields = genModelFieldsMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(genModelFields)) {
            return Result.fail("模型暂无字段信息");
        }
        CreateModelVo createModelVo = new CreateModelVo(genModel);
        createModelVo.setFields(genModelFields);
        String tableSql = null;
        if ("single".equals(genModel.getModelCharacter()) || "tree".equals(genModel.getModelCharacter())) {
            // 单表
            tableSql = CreateTableUtils.createTableSql(createModelVo);
        } else {
            return Result.fail("暂未开发....");
        }
        OnlineDataSource defaultDataSource = sparkCommonApi.queryDefaultDataSource();
        if (Objects.isNull(defaultDataSource)) {
            return Result.fail("请配置默认数据源");
        }
        System.out.println("创建表的SQL:");
        System.out.println(tableSql);
        // 存在表，删除表，强制同步
        DataSourceUtils dataSourceUtils = new DataSourceUtils(
                defaultDataSource.getDbDriver(),
                defaultDataSource.getDbUrl(),
                defaultDataSource.getDbUsername(),
                defaultDataSource.getDbPassword()
        );
        boolean drop = dataSourceUtils.deleteTable(genModel.getModelCode());
        if (!drop){
            return Result.fail("强制同步,删除 " + genModel.getModelCode() + " 表失败");
        }
        // 执行SQL语句
        boolean execute = dataSourceUtils.executeSql(tableSql);
        if (!execute) {
            return Result.fail("强制同步,创建 " + genModel.getModelCode() + " 表执行失败");
        }
        genModel.setModelSyncVersions(genModel.getModelSyncVersions() + 1);
        genModel.setModelSyncStatus(0);
        int index = baseMapper.updateById(genModel);
        return Result.flag(index, "同步成功", "同步失败");
    }
}
